package cn.backpackerxl.filter;

import cn.backpackerxl.service.StudentService;
import cn.backpackerxl.service.impl.StudentServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

/**
 * @author: backpackerxl
 * @create: 2021/12/9
 * @filename: IndexFilter
 **/

@WebFilter(filterName = "PageFilter", value = "/page")
public class PageFilter implements Filter {

    private StudentService studentService = new StudentServiceImpl();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String url = req.getRequestURI();
        HttpSession session = req.getSession();
        Object name = session.getAttribute("name");
        if (name == null || String.valueOf(name).length() == 0) {//说明未登录，重定向到登录页面
            req.setAttribute("warn", "请先登录！！！");
            req.getRequestDispatcher("/sing").forward(req, res);
            System.out.println("[\033[36m" + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date()) + "\033[0m] \033[42mINFO\033[0m" + " - 有人未登录访问了" + url);
            System.out.println("[\033[36m" + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date()) + "\033[0m] \033[42mINFO\033[0m" + " - 已经帮他重定向到登录页了");
            return;
        } else {//已登录放行
            filterChain.doFilter(req, res);
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
